<?php
/**
 * 管理员DAO
 * User: ZFC
 * Date: 2015/6/8
 * Time: 11:57
 */

namespace common\models\DAO;

use yii\db\ActiveRecord;
use common\models\CommonFunction;


class Admin extends ActiveRecord
{

    //数据库不存在的字段，需要单独做声明
    public $repeatPass;
    public $oldPass;
    public $roleName;

    public function attributeLabels()
    {
        return [
            'id'        => 'ID',
            'adminName' => '登录名',
            'adminPass' => '密码',
            'repeatPass' => '重复密码',
            'oldPass'   => '原密码',
            'realName' => '管理员姓名',
            'email' => '电子邮件',
            'phone' => '手机号码',
            'roleID' => '管理组',
            'encrypt' => '加密字符',
            'status' => '状态',
            'lastLoginIP' => '最后登录IP',
            'lastLoginTime' => '最后登录时间',
            'createTime' => '创建时间',
            'updateTime' => '更新时间',
        ];
    }

    public function rules()
    {
        return [
            [['adminName', 'adminPass', 'roleID', 'realName', 'repeatPass',], 'required', 'on' => 'add'],
            [['oldPass', 'adminPass', 'repeatPass',], 'required', 'on' => 'changePassword'],
            [['realName'], 'required', 'on'=>['edit', 'changeProfile']],
            [['adminName', 'email', 'phone'], 'unique', 'on' => 'add', 'message' => '{attribute}已重复，请重新填写'],
            ['roleID', 'compare', 'compareValue' => 1, 'operator' => '>', 'message' => '请选择管理员组', 'on'=>'add'],
            ['adminName', 'match', 'pattern' => '/^[a-zA-Z][a-zA-Z0-9_]{3,19}$/', 'message' => '{attribute}必须为4~20位的英文字母和数字的组合，不区分大小写'],
            ['adminPass', 'match', 'pattern' => '/^[\w\W]{8,22}$/', 'message' => '{attribute}必须为8~20位的任意字符'],
            ['repeatPass', 'compare', 'compareAttribute' => 'adminPass', 'on' => ['add', 'changePassword'], 'message' => '两次输入的密码必须一样'],
            ['status', 'default', 'value' => 1],
            ['email', 'email'],
            ['phone', 'match', 'pattern' => '/^1[0-9]{10}$/', 'message' => '{attribute}必须为1开头的11位纯数字'],
        ];
    }

    public function scenarios()
    {
        return [
            'default' => [],
            'add' => ['adminName', 'adminPass', 'repeatPass', 'roleID', 'realName', 'email', 'phone', 'status'],
            'edit' => ['adminPass', 'repeatPass', 'roleID', 'realName', 'email', 'phone', 'status'],
            'changeProfile' => ['realName', 'email', 'phone'],
            'changePassword' => ['adminPass','encrypt'],
        ];
    }


    public function beforeSave($insert)
    {
        //如果是修改密码择更改密码
        if(in_array($this->scenario, ['changePassword', 'add']) || ($this->scenario == 'edit' && $this->adminPass != '')){
            $this->encrypt = CommonFunction::getRandChar(6);
            $this->adminPass = $this->encryptPassword($this->adminPass, $this->encrypt);
        }else{
            unset($this->adminPass);
        }
        $this->repeatPass = null;
        $this->updateTime = time();
        if($insert) $this->createTime = $this->updateTime;
        return true;
    }

    /**
     * 更新最后登录信息
     */
    public function updateLastLogin(){
        $this->lastLoginTime = time();
        $this->lastLoginIP = CommonFunction::get_client_ip();
        $this->adminPass = null;
        $this->save();
    }

    /**
     * 取得用户信息
     * @param string $adminName
     * @return null|static
     */
    public function getAdmin($adminName){
        return $this->findOne(['adminName' => $adminName]);
    }


    public function getAgent(){
        return $this->hasOne(Agent::className(), ['id'=>'agentID']);
    }

    /**
     * 检查用户密码正确
     * @param string $password 密码
     * @return bool
     */
    public function validatePassword($password){
        $result = $this->encryptPassword($password, $this->encrypt);
        return ($result == $this->adminPass);
    }

    /**
     * 密码加密
     * @param string $password 密码
     * @param string $salt 用户盐
     * @return string
     */
    public function encryptPassword($password, $salt){
        $key = \Yii::$app->params['admin_key'];
        return CommonFunction::encryptPassword($password, $salt, $key);
    }


    public function genStatusText(){
        $status = $this->status;
        if($status == -1){
            return '禁用';
        }elseif($status === 1){
            return '正常';
        }else{
            return '未使用';
        }
    }

    /*
     * relation
     */
    public function getAdminRole(){
        return $this->hasOne(AdminRole::className(), ['id'=>'roleID']);
    }

}